package com.test.admin.quartz;

import com.test.admin.dao.ScriptDAO;
import com.test.admin.pojo.Script;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MysqlBackupJob implements Job, ApplicationContextAware {

    private static ScriptDAO scriptDAO;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MysqlBackupJob.scriptDAO = applicationContext.getBean(ScriptDAO.class);
    }

    //    @Autowired
//    public  void setScriptDAO(ScriptDAO scriptDAO) {
//        MysqlBackupJob.scriptDAO = scriptDAO;
//    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Script script = new Script();
        script.setName("com.test.admin.quartz.MysqlBackupJob");
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            //cmd运行windows命令  后面跟要执行的脚本文件  /c类似于cd
            //-u数据库用户名 -p数据库密码  设置编码  数据库名字
            String cmd = "cmd  /c \"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump\" -uroot -p123456 --set-charset=utf8 1901";
            System.out.println(cmd);
            Process process = Runtime.getRuntime().exec(cmd);//运行命令

            InputStream in = process.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in, "utf8");
            StringBuffer buffer = new StringBuffer("");
            String line = null;
            BufferedReader reader = new BufferedReader(inputStreamReader);
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                System.out.println(line);
            }
            FileOutputStream os = new FileOutputStream("E:/" + format.format(new Date()) + ".sql");
            OutputStreamWriter writer = new OutputStreamWriter(os, "utf-8");
            writer.write(buffer.toString());
            writer.flush();
            writer.close();
            reader.close();
            os.close();
            inputStreamReader.close();
            in.close();

            script.setResult("成功");

        } catch (IOException e) {
            e.printStackTrace();
            script.setResult(e.getMessage());
        }
        script.setLastExecTime(new Date());
        scriptDAO.updateLastExexTime(script);
    }

    public static void main(String[] args) {

    }
}
